/*
 Copyright 2012 Sven-Ove Bjerkan

 This file is part of KO-Ozi.

 KO-Ozi is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 KO-Ozi is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with KO-Ozi. If not, see <http://www.gnu.org/licenses/>.
 */
package com.koozi.auto;

import com.koozi.FileFolder;
import com.koozi.diff_match_patch;
import com.oziexplorer.OziAPI;
import com.oziexplorer.OziException;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 * This class handles the "master"-functionality
 *
 * @author Sven-Ove Bjerkan
 */
public class OziAutosave extends OziAuto implements Runnable {

    private int curTrackNo = 50;

    public OziAutosave(javax.swing.JLabel lblLastupdate) {
        super(lblLastupdate);
    }

    public void setCurTrackNo(int trackNo) {
        curTrackNo = trackNo;
    }

    // To run in another thread
    @Override
    public void run() {
        try {
            File f = null;
            diff_match_patch dmp = new diff_match_patch();
            // Always try to create projectfolder
            if (!createProjectfolder()) {
                System.err.println("Kunne ikke opprette mappe!");
            } else {
                // Save a "blank" track to compare with to see tracks that are used and not
                File blank_track = File.createTempFile("koozi", ".plt");
                blank_track.deleteOnExit();
                OziAPI.saveTrackFile(200, blank_track.getAbsolutePath());

                while (true) {
                    if (!OziAPI.findOzi()) {
                        JOptionPane.showMessageDialog(null, "OziExplorer kjører ikke!",
                                "Feilmelding", JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
                    }

                    // Save waypoints to a tempfile
                    f = File.createTempFile("koozi", ".wpt");
                    f.deleteOnExit();
                    OziAPI.saveWaypointFile(f.getAbsolutePath());

                    // Compare the tempfile with the last saved WP-file
                    String tmpWP = FileFolder.fileToString(f.getAbsolutePath());
                    
                    File oldF = new File(folderpath + "WP.wpt");
                    LinkedList<diff_match_patch.Diff> diff = null;
                    if (oldF.exists()) {
                        String oldWP = FileFolder.fileToString(folderpath + "WP.wpt");
                        diff = dmp.diff_main(tmpWP, oldWP, true);
                    }

                    // The WP-list is changed, so save it! :)
                    if (!oldF.exists() || diff.size() == 1) {
                        f = new File(folderpath + "WP.wpt");
                        if (f.isFile()) {
                            if (!f.canWrite()) {
                                System.err.println("Mangler skrivetilgang til WP-fil!");
                            } else if (!f.delete()) {
                                System.err.println("Greide ikke å slette WP-fil!");
                            }
                        }
                    }

                    if (diff != null)
                        diff.clear();
                    
                    oldF = null;
                    f = null;
                    OziAPI.saveWaypointFile(folderpath + "WP.wpt");
                    OziAPI.saveWaypointFlag(true);

                    for (int i = 2; i <= settings.getSaveTracks(); i++) {
                        // Compare the blank file with the current track
                        String blankPLT = FileFolder.fileToString(blank_track.getAbsolutePath());
                        f = File.createTempFile("koozi", ".plt");
                        f.deleteOnExit();
                        OziAPI.saveTrackFile(i, f.getAbsolutePath());
                        String tmpPLT = FileFolder.fileToString(f.getAbsolutePath());
                        diff = dmp.diff_main(blankPLT, tmpPLT, true);

                        boolean changed = false;
                        // The track is not blank...
                        if (diff.size() != 1) {
                            changed = true;
                            f = new File(folderpath + i + ".plt");
                            if (f.exists()) {
                                String oldPLT = FileFolder.fileToString(folderpath + i + ".plt");
                                diff = dmp.diff_main(tmpPLT, oldPLT, true);
                                // The track is changed, so save! :)
                                if (diff.size() == 1) {
                                    changed = false;
                                }
                            }
                            if (changed) {
                                boolean error = false;
                                if (f.exists()) {
                                    if (!f.canWrite()) {
                                        System.err.println("Mangler skrivetilgang til " + i + ".plt!");
                                        error = true;
                                    } else if (!f.delete()) {
                                        System.err.println("Greide ikke å slette " + i + ".plt!");
                                        error = true;
                                    }
                                }
                                if (!error) {
                                    OziAPI.saveTrackFile(i, folderpath + i + ".plt");
                                }
                            }
                        }
                        // The track is blank, but has existed - delete!
                        else {
                            f = new File(folderpath + i + ".plt");
                            if (f.exists())
                                f.delete();
                        }
                    }

                    /*
                     * // The tracking-tracks for (int i = 50; i <= curTrackNo;
                     * i++) { error = false; f = new File(folderpath + i +
                     * ".plt"); if (f.exists()) { if (!f.canWrite()) {
                     * System.err.println("Mangler skrivetilgang til " + i +
                     * ".plt!"); error = true; } else if (!f.delete()) {
                     * System.err.println("Greide ikke å slette " + i +
                     * ".plt!"); error = true; } }
                     *
                     * if (!error) { OziAPI.saveTrackFile(i, folderpath + i +
                     * ".plt"); } }
                     *
                     */

                    // Set the time of last update
                    cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1"));
                    lblLastupdate.setText(dateFormat.format(cal.getTime()));

                    // Sleep for the given interval
                    Thread.sleep((int) ((Double) settings.getOpenSaveInterval() * 60 * 1000));
                }
            }
        } catch (OziException ex) {
            Logger.getLogger(OziAutosave.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(OziAutosave.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (InterruptedException ex) {
            
        }    
    }
}
